package com.ailk.evaluation.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public abstract class BaseWebAction extends DispatchAction {
	
	public Log log = LogFactory.getLog(this.getClass());	

	private static ApplicationContext ctx = null;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
		return super.execute(mapping, form, request, response);
		
	}
	//protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String name)throws Exception{
	//	
	//}
	

	protected Object getBean(String name) {
		if (ctx == null)
			ctx = WebApplicationContextUtils
					.getRequiredWebApplicationContext(servlet
							.getServletContext());
		return ctx.getBean(name);
	}

	protected String uploadFile(HttpServletRequest request, FormFile file,
			String filepath) throws FileNotFoundException, IOException {
		String result = null;
		if (file != null && !file.getFileName().equals("")) {
			Date now = new Date();
			SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
			String relativityPath = (new StringBuilder()).append(
					request.getSession().getServletContext().getInitParameter(
							"uploadPath")).append("/").append(filepath).append(
					"/").append(adf.format(now)).toString();
			String uploadDir = request.getSession().getServletContext()
					.getRealPath(relativityPath);
			File dirPath = new File(uploadDir);
			if (!dirPath.exists())
				dirPath.mkdirs();
			String fileName = file.getFileName();
			int step = 0;
			for (File uploadfile = new File((new StringBuilder()).append(
					uploadDir).append("/").append(fileName).toString()); uploadfile
					.exists(); uploadfile = new File((new StringBuilder())
					.append(uploadDir).append("/").append(fileName).toString())) {
				step++;
				fileName = formatSamename(fileName, step);
			}

			fileName = (new StringBuilder()).append(
					Math.abs((new Random()).nextInt())).append(
					fileName.substring(fileName.lastIndexOf("."))).toString();
			result = (new StringBuilder()).append(relativityPath).append("/")
					.append(fileName).toString();
			InputStream stream = file.getInputStream();
			OutputStream bos = new FileOutputStream((new StringBuilder())
					.append(uploadDir).append("/").append(fileName).toString());
			int bytesRead = 0;
			byte buffer[] = new byte[8192];
			while ((bytesRead = stream.read(buffer, 0, 8192)) != -1)
				bos.write(buffer, 0, bytesRead);
			bos.close();
			stream.close();
			file.destroy();
		}
		return result;
	}

	private String formatSamename(String name, int step) {
		String result = "";
		int start = name.lastIndexOf("(");
		int end = name.lastIndexOf(")");
		int doc = name.lastIndexOf(".");
		if (start == -1 && end == -1)
			result = (new StringBuilder()).append(name.substring(0, doc))
					.append("(").append(step).append(")").append(
							name.substring(doc)).toString();
		else
			result = (new StringBuilder()).append(name.substring(0, start))
					.append("(").append(step).append(name.substring(end))
					.toString();
		return result;
	}
}
